﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;

namespace GreetingCreatorGraphicUserControls.BackgroundAnimationCustomControl
{
    public class ItemFactory
    {
        public UserControl CreateItem(Grid grid)
        {
            if (grid == null)
                throw new ArgumentNullException("Input parameter grid cannot be null!");

            UserControl item = InternalCreateItem();
            item.Name = Guid.NewGuid().ToString();
            item.RenderTransform = CreateTransformGroupForItem();
            SetRandomItemStartPosition(item, grid.ActualWidth);

            ///Todo: Maybe Remove or improve
            item.Opacity = Double.Parse("0." + RandomService.RandomNumber(3, 9));

            return (item);
        }

        private UserControl InternalCreateItem()
        {
            int randomItemToUse = RandomService.RandomNumber(0, 2);

            if (randomItemToUse == 0)
                return new ThemeObject0Control();
            else
                return new ThemeObject1Control();
        }

        private TransformGroup CreateTransformGroupForItem()
        {
            double objctScaleSize = RandomService.GetValidRandomObjectScaleSize();

            var transformGroup = new TransformGroup();
            transformGroup.Children.Add(new ScaleTransform {ScaleX = objctScaleSize, ScaleY = objctScaleSize});
            transformGroup.Children.Add(new RotateTransform
                                            {
                                                CenterX = RandomService.GetRandomCenterX(),
                                                Angle = RandomService.GetRandomAngle()
                                            });
            transformGroup.Children.Add(new TranslateTransform());

            return (transformGroup);
        }

        private void SetRandomItemStartPosition(UserControl item, double gridWidth)
        {
            int gridWidthAsInt = Convert.ToInt32(gridWidth);
            int defualtMarginValue = 0;
            int startPosition = -150;
            item.Margin = new Thickness(RandomService.RandomNumber(defualtMarginValue, gridWidthAsInt),
                                        RandomService.RandomNumber(startPosition, 0), defualtMarginValue,
                                        defualtMarginValue);
        }
    }
}